import fs from 'fs';
import { fromMarkdown } from 'mdast-util-from-markdown';

const markdown = fs.readFileSync('./CHANGELOG.md', 'utf-8');
const ast = fromMarkdown(markdown);

const info = {
  version: '',
  time: '',
  fns: [],
};
ast.children.forEach((node, index) => {
  if (node.type === 'heading' && node.depth === 2) {
    // 解析版本号和日期
    const headerContent = node.children[0].value;
    const versionMatch = headerContent.match(/V(\d+\.\d+\.\d+)/);
    const dateMatch = headerContent.match(/(\d{4}\.\d+\.\d+)/);
    if (versionMatch && dateMatch) {
      info.version = versionMatch[0];
      info.time = dateMatch[0];
    }
  } else if (node.type === 'heading' && node.depth === 3) {
    // 新功能或修复部分的标题
    const section = {
      title: node.children[0].value,
      lists: []
    };
    info.fns.push(section);

    // 下一个节点应该是一个列表，包含这个部分的具体条目
    const nextNode = ast.children[index + 1];
    if (nextNode && nextNode.type === 'list') {
      nextNode.children.forEach((listItem) => {
        const item = {
          title: '',
          desc: [],
          url: '',
          link: '',
          author: ''
        };

        listItem.children.forEach((part) => {
          if (part.type === 'paragraph') {
            part.children.forEach((element) => {
              switch (element.type) {
                case 'text':
                  item.title += element.value;
                  break;
                case 'link':
                  item.link = element.url;
                  item.author = element.children[0].value;
                  break;
                case 'image':
                  item.url = element.url;
                  break;
              }
            });
          } else if (part.type === 'list') {
            item.desc = part.children.map(descItem => descItem.children[0].children.map(text => text.value).join(' '));
          }
        });

        section.lists.push(item);
      });
    }
  }
});

console.log(info);
fs.writeFileSync('./info111.json', JSON.stringify(info, null, 2));
